package com.project;

import com.project.servlet.TestServlet;
import com.project.servlet.student.AddServlet;
import com.project.servlet.student.CutAllServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.Servlet;

public class Main {
    public Main(){
        //创建Tomcat对象
        Tomcat tomcat = new Tomcat();
        //设置启动端口
        tomcat.setPort(8088);
        //引导HTTP引擎
        tomcat.getConnector();

        AnnotationConfigApplicationContext springContext =
                new AnnotationConfigApplicationContext(MyBatisConfig.class);

        //得到WEB上下文全局对象
        Context webContxt = tomcat.addContext("",null);
        this.registerServlet(webContxt,
                springContext.getBean(CutAllServlet.class),"/student/cutAll");
        this.registerServlet(webContxt,
                new TestServlet(),"/test");
        this.registerServlet(webContxt,new AddServlet(),"/add");

        try {
            //启动tomcat
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void registerServlet(Context webContxt,
          Servlet servletObj,String url){
        //注册servlet类。第一个参数为上下文对象
        //第二个参数为servlet名称，第三个参数为servlet对象
        Wrapper w = Tomcat.addServlet(webContxt,
                servletObj.getClass().getSimpleName(),servletObj);
        //容器启动，是否完成servlet的初始化动作（init）
        //为0或正数，表示容器启动就完成servlet初始化
        //默认或负数，表示第一次访问该servlet完成初始化
        w.setLoadOnStartup(0);
        //配置servlet的客户端访问路径
        w.addMapping(url);
    }
    public static void main(String[] args) {
        new Main();
    }
}
